﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using HandyControl.Controls;
using clf.weighing.entity;

namespace weighing
{
    /// <summary>
    /// 物价管理 的交互逻辑
    /// </summary>
    public partial class MeartialPriceWindow : GlowWindow
    {
        private Material? material;

        private decimal money = new decimal(0.00);

        public MeartialPriceWindow(Material material)
        {
            InitializeComponent();

            CommonFunction.ShowCustomIcon(this);

            this.material = material;

            if(this.material != null)
            {
                this.buyPriceAllowCb.IsChecked = this.material.allowInputBuyPrice;
                this.sallePriceAllowCb.IsChecked = this.material.allowInputSalePrice;
            }
        }

        #region windows event 

        private void GlowWindow_Loaded(object sender, RoutedEventArgs e)
        {
            this.MaterialTb.Text = material?.name;
        }

        private void GlowWindow_ContentRendered(object sender, EventArgs e)
        {
            this.MainTabControl.SelectedIndex = 0;
            LoadData();
        }

        private void GlowWindow_KeyUp(object sender, System.Windows.Input.KeyEventArgs e)
        {
            if (e.Key == Key.Escape) this.Close();
        }

        #endregion

        //加载数据
        private void LoadData()
        {
            if (this.InPriceTI.IsSelected == true)
            {
                var data = MaterialPriceDao.Instance.SelectPricesByMaterialId((long)material.id, MaterialPriceType.Buy);
                this.InDataLv.ItemsSource = data?.Select((i) => { return new MaterialPriceVo(i); }).ToList();
            }

            if (this.OutPriceTI.IsSelected == true)
            {
                var data =MaterialPriceDao.Instance.SelectPricesByMaterialId((long)material.id, MaterialPriceType.Sale);
                this.OutDataLv.ItemsSource = data?.Select((i) => { return new MaterialPriceVo(i); }).ToList();
            }
        }

        private void MainTabControl_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (IsLoaded) LoadData();
        }

        private void RefreshBtn_Click(object sender, RoutedEventArgs e)
        {
            LoadData();
        }

        private void UpdateMoneyBtn_Click(object sender, RoutedEventArgs e)
        {
            this.updateDrawer.IsOpen = true;
        }

        private void CancelBtn_Click(object sender, RoutedEventArgs e)
        {
            this.activeTimePicker.SelectedDateTime = null;
            this.endDateTimePicker.SelectedDateTime = null;
            this.PriceTb.Text = string.Empty;
            this.saveBtn.IsChecked = false;
            this.updateDrawer.IsOpen = false;
        }

        private void SaveBtn_Click(object sender, RoutedEventArgs e)
        {
            if (CheckInput())
            {
                int res ;
                var type = this.InPriceTI.IsSelected == true ? MaterialPriceType.Buy : MaterialPriceType.Sale;
                MaterialPrice? currPrice =MaterialPriceDao.Instance.GetMaterialCurrPrice((long)material.id, type);
                if(currPrice == null)
                {
                    var np = BuildMaterialPrice();
                    res =MaterialPriceDao.Instance.Sqlite.Insert(np);
                }
                else
                {                  
                  res =  Update(currPrice);
                }
                if(res > 0) {
                    Growl.SuccessGlobal("保存成功" );
                    this.saveBtn.IsChecked = false;
                    this.updateDrawer.IsOpen = false;
                    this.activeTimePicker.SelectedDateTime=null;
                    this.endDateTimePicker.SelectedDateTime = null;
                    LoadData();
                    CancelBtn_Click(null,null);
                } 
                else
                {                    
                    Growl.ErrorGlobal("保存失败！");
                    this.saveBtn.IsChecked = false;
                }                
            }
            this.saveBtn.IsChecked = false;
        }

        //更新 事务操作
        private int Update(MaterialPrice currPrice)
        {          
            var newPrice = BuildMaterialPrice();
            var oldPrice = new MaterialPrice()
            {
                id = currPrice.id,
                failureTime = newPrice.effectiveTime                
            };       
           
          return MaterialPriceDao.Instance.UpdatePrice(oldPrice,newPrice);
        }

        //检查输入
        private bool CheckInput()
        {
            try
            {
                money = Convert.ToDecimal(this.PriceTb.Text.Trim());
            }
            catch (Exception ex)
            {
                Growl.Info("输入的价格不正确 ！"+ex.Message);               
                return false;
            }
            if (activeTimePicker.SelectedDateTime == null || activeTimePicker.SelectedDateTime < DateTime.Now)
            {
                Growl.Info("生效时间必须大于当前时间 ！");   
                return false;
            }

            if (activeTimePicker.SelectedDateTime== null || endDateTimePicker.SelectedDateTime <= activeTimePicker.SelectedDateTime) {
                Growl.Info("失效时间必须大于生效时间 ！");     
                return false;
            }

            return true;
        }

        private MaterialPrice BuildMaterialPrice()
        {
            var mp = new MaterialPrice()
            {
                id = MyHelper.Snowflake.Instance().GetId(),
                price = money,
                type = this.MainTabControl.SelectedIndex,
                materialId = material.id,
                materialName = material.name,
                addUserId = App.CurrentUser.id,
                belong = (int)DataBelong.Enterprise,
                addTime = DateTime.Now,
                affiliatedCompanyId = App.CurrentCompanyVo.Id,
                effectiveTime = this.activeTimePicker.SelectedDateTime,
                failureTime = this.endDateTimePicker.SelectedDateTime,
                status = 1
            };
            return mp;
        }

        #region 允许过磅时临时输入

        private void sallePriceAllowCb_Checked(object sender, RoutedEventArgs e)
        {
            material.allowInputSalePrice = true;
            MaterialDao.Instance.Sqlite.Update(material);
        }

        private void sallePriceAllowCb_Unchecked(object sender, RoutedEventArgs e)
        {
            material.allowInputSalePrice = false;
            MaterialDao.Instance.Sqlite.Update(material);
        }

        private void buyPriceAllowCb_Checked(object sender, RoutedEventArgs e)
        {
            material.allowInputBuyPrice = true;
            MaterialDao.Instance.Sqlite.Update(material);
        }

        private void buyPriceAllowCb_Unchecked(object sender, RoutedEventArgs e)
        {
            material.allowInputBuyPrice = false;
            MaterialDao.Instance.Sqlite.Update(material);
        }
        #endregion
    }
}
